<template>
    <div>
        <!-- @closed="destroyTerminal" -->
        <el-dialog v-model="open" center title="XTerm终端" append-to-body width="600px"  >
            <div ref="terminalRef" class="terminal-container"></div>
        </el-dialog>
    </div>
</template>

<script setup>

import { ref, nextTick } from 'vue';
import { Terminal } from 'xterm';
import { FitAddon } from '@xterm/addon-fit';
const open = ref(false);
// 打开弹窗
const openDialog = () => {
    onClosed()
    open.value = true;
    onOpen();
};
// 关闭弹窗
const closeDialog = () => {
    open.value = false;
    onClosed();
};

defineExpose({
  openDialog,
  closeDialog
});
const emit = defineEmits(['update:visible']);

const terminalRef = ref(null);
let terminal = null;
const fitAddon = new FitAddon();

// 弹窗打开时初始化
const onOpen = () => {
  nextTick(() => {
    if (!terminal && terminalRef.value) {
      terminal = new Terminal({
        cursorBlink: true,
        foregroundColor: 'black'
      });
      terminal.loadAddon(fitAddon);
      terminal.open(terminalRef.value);
      terminal.focus();
      fitAddon.fit(); // 调整尺寸
      // terminal.write(' \x1B[1;3;31mxterm.js\x1B[0m $ ');
      // 可选：处理窗口大小变化
      // 监听用户输入
      terminal.onData((data) => {
        // 防抖处理
        if (data === '\r') {
          return;
        }
        terminal.write(`\x1B[1;3;31m${data}\x1B[0m `); // 将输入回显到终端
      });
      window.addEventListener('resize', handleResize);
    }
  });
};

// 调整终端尺寸
const handleResize = () => {
  fitAddon.fit();
};

// 弹窗关闭时清理
const onClosed = () => {
  if (terminal) {
    terminal.dispose();
    terminal = null;
    window.removeEventListener('resize', handleResize);
  }
};

</script>

<style lang="scss" scoped>
@import 'xterm/css/xterm.css';

.terminal-container {
  width: 100%;
  height: 400px; /* 固定高度或根据弹窗自适应 */
  background: black;
}
.xterm-viewport { 
  overflow: hidden !important; /* 避免滚动条问题 */
}

</style>